<?php


namespace app\api\controller;


use app\BaseController;
use app\common\lib\pay\weixin\lib\database\WxPayNotifyResults;
use app\common\lib\pay\weixin\lib\database\WxPayResults;
use app\common\lib\pay\weixin\lib\WxPayConfig;
use think\facade\Cache;

class Notify extends BaseController
{
    public function weixin() {
        // 测试数据是否在服务端能接收。。。
        //$data = input("param.");
        $data = $this->request->getInput();
       /*$data = "<xml><appid><![CDATA[wx1c1a239592ffc8ba]]></appid>
<bank_type><![CDATA[OTHERS]]></bank_type>
<cash_fee><![CDATA[1]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[N]]></is_subscribe>
<mch_id><![CDATA[1442075302]]></mch_id>
<nonce_str><![CDATA[hmcjzm4l8bnuuw1d0l04vl33qkklptdy]]></nonce_str>
<openid><![CDATA[ot2rs0AoII8lxju-rzIFUuMGFVSg]]></openid>
<out_trade_no><![CDATA[85736353756610560]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[FC69150EBFE5E3BA5A714866D5DB9AF9E989E79D542E87AB200C06DB671DE9D4]]></sign>
<time_end><![CDATA[20200331221404]]></time_end>
<total_fee>1</total_fee>
<trade_type><![CDATA[NATIVE]]></trade_type>
<transaction_id><![CDATA[4200000566202003312249438857]]></transaction_id>
</xml>
";*/


        file_put_contents("/tmp/a.log", $data, FILE_APPEND);

        // 1、验证签名，防止伪造
        $resObj = new WxPayResults();
        try {
            $config = new WxPayConfig();
            $resData = WxPayResults::Init($config, $data);
            file_put_contents("/tmp/a1.log", $resData, FILE_APPEND);
        }catch (\Exception $e) {
            //file_put_contents("/tmp/a2.log", 'dsadsa', FILE_APPEND);
            //通知微信错误
            $resObj->SetData('return_code', 'FAIL');
            $resObj->SetData('return_msg', $e->getMessage());
            file_put_contents("/tmp/a2.log", $e->getMessage(), FILE_APPEND);
            return $resObj->toXml();
        }
        // 2、支付状态校验
        if(!$resData  || !isset($resData['result_code'])
            || !isset($resData['return_code'])
            || $resData['result_code'] !== "SUCCESS"
            || $resData['return_code'] !== "SUCCESS"
        ) {
            file_put_contents("/tmp/a4.log", $resData, FILE_APPEND);
            //失败
            //通知微信错误
            $resObj->SetData('return_code', 'FAIL');
            $resObj->SetData('return_msg', 'error');
            return $resObj->toXml();
        }

        file_put_contents("/tmp/a5.log", $data, FILE_APPEND);
        // 3、支付金额校验（包含订单是否存在校验）
        $order_id = $resData['out_trade_no'];
        $orderModel = new \app\common\model\mysql\Order();
        $order = $orderModel->where('order_id', $order_id)->find();
        $redisOrderData = Cache::store('redis')->hget(config('pay.pay_status_key'), $order_id);
        file_put_contents("/tmp/a6.log", $resData, FILE_APPEND);
        if ($order && $order['status'] == 1) {
            file_put_contents("/tmp/a7.log", $redisOrderData, FILE_APPEND);
            //修改mysql和redis支付状态
            //把支付状态放入redis
            if (!empty($redisOrderData)) {
                $redisOrderData = json_decode($redisOrderData, 1);
                $redisOrderData['pay_status'] = 1;
            } else {
                $redisOrderData = [
                    'pay_status'=> 1,
                    'pay_type'=> 'weixin',
                    'create_time'=> time()
                ];
            }
            file_put_contents("/tmp/a1111.log", $redisOrderData, FILE_APPEND);
            try {
                Cache::store('redis')->hset(config('pay.pay_status_key'), $order_id, json_encode($redisOrderData));
                $orderModel->where('order_id', $order_id)->save(['status'=> 2]);
            } catch (\Exception $e) {
                //数据修改失败   还需回调
                file_put_contents("/tmp/a8.log", $e->getMessage(), FILE_APPEND);
                $resObj->SetData('return_code', 'FAIL');
                $resObj->SetData('return_msg', 'error');
                return $resObj->toXml();
            }

        }
        file_put_contents("/tmp/a9.log", 'success', FILE_APPEND);

        // 最后修改订单支付状态，微信回调我们自己的异步通知接口，告知微信，已经修改成功，不要回调我们了
        $resObj->SetData('return_code', 'SUCCESS');
        $resObj->SetData('return_msg', 'OK');
        return $resObj->toXml();
    }

    public function aliPay() {

    }
}